<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="100px">
        <el-form-item label="工段">
          <el-select
            v-model="searchParam.workshopSectionId"
            placeholder="请选择工段"
            clearable
            filterable
            @change="changeWorkshopSection"
          >
            <el-option
              v-for="item in workshopSectionList"
              :key="item.id"
              :label="item.workshopSectionCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工序">
          <el-select
            v-model="searchParam.processId"
            placeholder="请选择工序"
            clearable
            filterable
            @change="processChange"
          >
            <el-option
              v-for="item in processList"
              :key="item.id"
              :label="item.processCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生产线">
          <el-select
            v-model="searchParam.processEquipId"
            placeholder="请选择生产线"
            clearable
            filterable
            @change="processEquipChange"
            :filter-method="customFilter2"
          >
            <el-option
              v-for="item in filteredOptions2"
              :key="item.id"
              :label="item.equipCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备">
          <el-select
            v-model="searchParam.equipId"
            placeholder="请选择设备"
            clearable
            filterable
            @change="equipChange"
            :filter-method="customFilter3"
          >
            <el-option
              v-for="item in filteredOptions3"
              :key="item.equipId"
              :label="item.equipName"
              :value="item.equipId"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="产品型号">
          <el-input
            v-model="searchParam.productModel"
            placeholder="请输入产品型号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item> -->
        <el-form-item label="客户">
          <el-select
            v-model="searchParam.projectId"
            placeholder="请选择客户"
            clearable
            filterable
            @change="changeProject"
          >
            <el-option
              v-for="item in projectList"
              :key="item.projectId"
              :label="`${item.projectName}`"
              :value="item.projectId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="型号描述">
          <el-select
            v-model="searchParam.productModel"
            placeholder="请选择型号描述"
            clearable
            filterable
            :filter-method="customFilter1"
            @change="productModelChange"
          >
            <el-option
              v-for="item in filteredOptions1"
              :key="item.productModel"
              :label="`${item.productModelName ?? ''}`"
              :value="item.productModel"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品型号">
          <el-select
            v-model="searchParam.productModel"
            placeholder="请选择产品型号"
            clearable
            filterable
            :filter-method="customFilter"
            @change="productModelChange"
          >
            <el-option
              v-for="item in filteredOptions"
              :key="item.productModel"
              :label="`${item.productModel}`"
              :value="item.productModel"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="参数名称">
          <el-select
            v-model="searchParam.parameterId"
            placeholder="请选择参数名称"
            clearable
            filterable
            :filter-method="customFilter4"
            :disabled="!(searchParam.equipId && searchParam.productModel)"
            :loading="collectParamLoading"
            @change="processParameterChange"
          >
            <el-option
              v-for="item in filteredOptions4"
              :key="item.id"
              :label="item.parameterDesc"
              :value="item.id"
            />
            <template #loading>
              <svg class="circular" viewBox="0 0 50 50">
                <circle class="path" cx="25" cy="25" r="20" fill="none" />
              </svg>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="异常处理">
          <el-select
            v-model="searchParam.dealMode"
            placeholder="请选择异常处理"
            clearable
          >
            <el-option
              v-for="item in useDictionary('PsmDealMode')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="异常发生时间">
          <el-date-picker
            v-model="searchParam.collectionTimeSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getcollectionTime"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="resetHandle">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <!--      <template #header>-->
      <!--        <el-button type="success" plain @click="openDialog()"><i-ep-plus />新增</el-button>-->
      <!--                -->
      <!--      </template>-->

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        :maxHeight="tableHeight"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          label="工段"
          prop="workshopSectionCode"
          min-width="80"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="工序"
          prop="processCode"
          min-width="80"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="生产线"
          prop="processEquipCode"
          min-width="80"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="设备"
          prop="equipName"
          min-width="130"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="客户"
          prop="projectName"
          min-width="120"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="型号描述"
          prop="productModelName"
          min-width="110"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="产品型号"
          prop="productModel"
          min-width="110"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="程序名"
          prop="programName"
          min-width="120"
          show-overflow-tooltip
          align="center"
        />
        <!--        <el-table-column label="采集时间" prop="collectionTime" min-width="100" show-overflow-tooltip>-->
        <!--        </el-table-column>-->

        <el-table-column
          label="参数名称"
          prop="parameterDesc"
          min-width="180"
          show-overflow-tooltip
        />

        <!-- <el-table-column
          label="工单生成时间"
          prop="createTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        /> -->

        <el-table-column
          label="取样频度"
          prop="samplingFrequency"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="{ $index, row }">
            <!-- {{ useDictionary("ScaCollectFrequency", row.samplingFrequency) }} -->
            {{ row.samplingFrequency }}

            <!-- <span
              v-if="row.collectionFrequencyTime && row.samplingFrequency == '2'"
              >&nbsp; {{ row.collectionFrequencyTime
              }}{{
                row.collectionFrequencyUnit === "s"
                  ? "秒"
                  : row.collectionFrequencyUnit === "m"
                  ? "分钟"
                  : ""
              }}
            </span> -->
          </template>
        </el-table-column>
        <el-table-column
          label="异常发生时间"
          prop="createTime"
          min-width="160"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="最近一次处理时间"
          prop="lastUpdateTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />

        <el-table-column
          label="发送邮件"
          prop="isSendMail"
          min-width="100"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ useDictionary("YesNo", scope.row.isSendMail) }}
          </template>
        </el-table-column>
        <el-table-column
          label="生成工单"
          prop="isOrder"
          min-width="100"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ useDictionary("YesNo", scope.row.isOrder) }}
          </template>
        </el-table-column>
        <el-table-column
          label="工单状态"
          prop="workOrderStatus"
          min-width="80"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{
              useDictionary("PsmOrderStatus", scope.row.workOrderStatus) || ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="第一责任人"
          prop="responsiblePersonName"
          min-width="100"
          align="center"
          show-overflow-tooltip
        />
        <!--        <el-table-column label="工艺数据类别" prop="processDataType" min-width="100" show-overflow-tooltip>-->
        <!--        </el-table-column>-->
        <!-- <el-table-column
          label="实际值"
          prop="referenceValue"
          min-width="80"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="控制范围"
          prop="monitoringResult"
          min-width="140"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{ scope.row.lowerLimitValue }} - {{ scope.row.upperLimitValue }}
          </template>
        </el-table-column>
        <el-table-column
          label="监控结果"
          prop="monitoringResultText"
          min-width="100"
          show-overflow-tooltip
        /> -->
        <el-table-column fixed="right" label="操作" width="80" align="center">
          <template #default="scope">
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="查看"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialogdetail(scope.row)"
              >
                <i-ep-search />
              </el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="处理"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                v-if="authAllPerm(['psm:gdlb:edit']) && scope.row.isOrder == 1"
                @click="openDialog(scope.row)"
              >
                <i-ep-edit />
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <psmworkorder-edit
      :key="dayjsValue"
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import {
  useTable,
  useDownload,
  useDictionary,
  useComputeTableHeight,
} from "@/utils/useTable";
import request from "@/utils/request";
import {
  getMdmProcessEquipApi,
  getMdmprocessListApi,
  getMdmproductinfosApi1,
  getMdmProcessProjectApi,
} from "@/utils/commonData";
import dayjs from "dayjs";
import _ from "lodash-es";
import { authAllPerm } from "@/utils/index";

defineOptions({
  name: "PSMPSMABNORMALINFORMATION",
  inheritAttrs: false,
});

function processParameterChange(name: string) {
  if (name) {
    const current: any =
      collectParamList.value?.filter((e: any) => e.id === name)[0] ?? {};
    searchParam.value.parameterDesc = current.parameterDesc || "";
    searchParam.value.parameterName = current.parameterName || "";
  } else {
    searchParam.value.parameterDesc = "";
    searchParam.value.parameterName = "";
  }
}

const collectParamList = ref(<any>[]);
const collectParamLoading = ref(false);
async function getCollectParamList(id?: string) {
  collectParamLoading.value = true;
  const res: any = await request({
    url: "/dmpDosPcm/psmparammonitorrule/getParameterList",
    method: "post",
    data: {
      processId: searchParam.value.processId,
      equipIds: searchParam.value.equipId ? [searchParam.value.equipId] : "",
      productModels: searchParam.value.productModel
        ? [searchParam.value.productModel]
        : [],
    },
  }).catch((e) => {
    collectParamLoading.value = false;
  });
  if (res.code === 200) {
    collectParamList.value = res.data || [];
    filteredOptions4.value = res.data || [];
    collectParamLoading.value = false;
  }
}
const filteredOptions4 = ref<any>([]);
// 使用 debounce 包装过滤方法
const customFilter4 = _.debounce((query: any) => {
  if (!query) {
    filteredOptions4.value = [...collectParamList.value];
    return;
  }
  filteredOptions4.value = collectParamList.value.filter((option: any) =>
    option.parameterDesc?.toLowerCase().includes(query.toLowerCase())
  );
}, 300); // 延迟 300ms

// 获取产品型号列表
const productList = ref<any>([]);
async function getProductList() {
  const list: any =
    (await getMdmproductinfosApi1({ deviceId: searchParam.value.equipId })) ||
    [];
  productList.value = [...list];
}

// 请求参数
const requestApi = "/dmpDosPcm/psmExceptionRecord/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  processId: "",
  processCode: "",
  processEquipId: "",
  equipId: "",
  equipCode: "",
  productModel: "",
  projectId: "",
  projectCode: "",
  projectName: "",
  workOrderStatus: "",
  programName: "",
  collectionTimeSearch: [
    dayjs().subtract(1, "month").format("YYYY-MM-DD HH:mm:ss"),
    dayjs().format("YYYY-MM-DD HH:mm:ss"),
  ],
  collectionTimeStart: "",
  collectionTimeEnd: "",
  dealMode: "",
  parameterName: "", // 工艺参数
  parameterDesc: "", // 工艺描述
  parameterId: "", // 工艺参数id
};

const deleteParam = {
  api: "/dmpDosPcm/psmworkorder/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

// 定义tableHeight, 将计算注入dataCallBack回调中
const tableHeight = ref();
function dataCallBack(data: any) {
  setTimeout(() => {
    tableHeight.value = useComputeTableHeight();
  }, 100);
  return data;
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError,
  deleteParam
);

onMounted(async () => {
  getTableList();
  await getProcessList();
  await getProcessEquipList();
  await getEquipList();
  // await getProductList();
  await getProjectList();
  getProductModelList();
  getWorkshopSectionList();
  // searchParam.value.collectionTimeSearch = [
  //   dayjs().subtract(1, "month").format("YYYY-MM-DD"),
  //   dayjs().format("YYYY-MM-DD"),
  // ];
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/dmpDosPcm/psmworkorder/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

const dayjsValue = ref(dayjs().valueOf());
/** 打开工单管理表单弹窗 */
function openDialog(roleObj?: Object) {
  dayjsValue.value = dayjs().valueOf();
  if (roleObj) {
    addDialog.title = "工单处理";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增工单管理";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开工单管理表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "异常信息详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getcollectionTime(data: any) {
  if (data) {
    searchParam.value.collectionTimeStart = data[0];
    searchParam.value.collectionTimeEnd = data[1];
  } else {
    searchParam.value.collectionTimeStart = "";
    searchParam.value.collectionTimeEnd = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/dmpDosPcm/psmworkorder/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}
// 获取工序列表
const processList = ref<any>([]);
async function getProcessList() {
  processList.value = (await getMdmprocessListApi({})) || [];
}
async function processChange(id: string) {
  searchParam.value.equipId = "";
  searchParam.value.equipCode = "";
  searchParam.value.productModel = "";
  searchParam.value.processEquipId = "";
  searchParam.value.parameterName = "";
  searchParam.value.parameterDesc = "";
  searchParam.value.parameterId = "";
  if (id) {
    const current: any =
      processList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.processCode = current.processCode || "";
  } else {
    searchParam.value.processCode = "";
  }
  getProcessEquipList();
  getEquipList();
  getProjectList();
  getProductModelList();
  if (searchParam.value.equipId && searchParam.value.productModel) {
    getCollectParamList();
  }
}

function productModelChange() {
  searchParam.value.parameterName = "";
  searchParam.value.parameterDesc = "";
  searchParam.value.parameterId = "";
  if (searchParam.value.equipId && searchParam.value.productModel) {
    getCollectParamList();
  }
}

// 通过工序查询设备列表
const equipList = ref(<any>[]);
async function getEquipList() {
  const { data } = await request({
    // url: "iotadmin/scaequipinfo/getList",
    // method: "post",
    // data: {},
    url: "/dmpDosPcm/equipmentInfo/getList",
    method: "post",
    data: {
      processCode: searchParam.value.processCode,
      processId: searchParam.value.processId,
      workshopSectionId: searchParam.value.workshopSectionId,
      processEquipId: searchParam.value.processEquipId,
    },
  });
  equipList.value = data || [];
  filteredOptions3.value = data || [];
}
const filteredOptions3 = ref<any>([]);
// 使用 debounce 包装过滤方法
const customFilter3 = _.debounce((query: any) => {
  if (!query) {
    filteredOptions3.value = [...equipList.value];
    return;
  }
  filteredOptions3.value = equipList.value.filter((option: any) =>
    option.equipName?.toLowerCase().includes(query.toLowerCase())
  );
}, 300); // 延迟 300ms

function equipChange(id: string) {
  searchParam.value.parameterName = "";
  searchParam.value.parameterDesc = "";
  searchParam.value.parameterId = "";
  searchParam.value.productModel = "";
  collectParamList.value = [];
  filteredOptions4.value = [];
  if (id) {
    const current: any =
      equipList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.equipCode = current.equipCode || "";
    // getProductList();
    if (searchParam.value.equipId && searchParam.value.productModel) {
      getCollectParamList();
    }
  } else {
    searchParam.value.equipCode = "";
    // getProductList();
  }
  getProjectList();
  getProductModelList();
}

// 获取项目列表
const projectList = ref([]);
const getProjectList = async () => {
  searchParam.value.projectId = "";
  projectList.value = [];
  await request({
    // url: `mdm/mdmprojectinfo/getList`,
    url: "/dmpDosPcm/psmparammonitorrule/exist/project/options",
    method: "post",
    data: {
      processId: searchParam.value.processId,
      workshopSectionId: searchParam.value.workshopSectionId,
      equipIds: searchParam.value.equipId ? [searchParam.value.equipId] : [],
      processEquipId: searchParam.value.processEquipId,
    },
  }).then((res) => {
    projectList.value = res.data;
  });
};
// 改变项目列表
const changeProject = (e: string) => {
  productModelList.value = [];
  filteredOptions.value = [];
  searchParam.value.productModel = "";
  if (e) {
    const current: any =
      projectList.value?.filter((item) => item.id == e)[0] ?? {};
    searchParam.value.projectName = current.projectName;
    searchParam.value.projectCode = current.projectCode;
    getProductModelList(e);
  } else {
    searchParam.value.projectName = "";
    searchParam.value.projectCode = "";
    getProductModelList();
  }
};

// 根据项目获取产品型号
// 获取产品型号
const productModelList = ref([]);
const filteredOptions = ref([]);
const getProductModelList = async (id?: string) => {
  searchParam.value.productModel = "";
  productModelList.value = [];
  filteredOptions.value = [];
  filteredOptions1.value = [];
  await request({
    // url: "mdm/mdmproductinfo/getList",
    url: "/dmpDosPcm/psmparammonitorrule/exist/product/options",
    method: "post",
    data: {
      projectIds: searchParam.value.projectId
        ? [searchParam.value.projectId]
        : [],
      processId: searchParam.value.processId,
      workshopSectionId: searchParam.value.workshopSectionId,
      equipIds: searchParam.value.equipId ? [searchParam.value.equipId] : [],
      processEquipId: searchParam.value.processEquipId,
    },
  }).then((res) => {
    productModelList.value = res.data;
    filteredOptions.value = [...productModelList.value];
    filteredOptions1.value = [...productModelList.value];
  });
};

// 使用 debounce 包装过滤方法
const customFilter = _.debounce((query: any) => {
  if (!query) {
    filteredOptions.value = [...productModelList.value];
    return;
  }
  filteredOptions.value = productModelList.value.filter((option: any) =>
    option.productModel.toLowerCase().includes(query.toLowerCase())
  );
}, 300); // 延迟 300ms

const filteredOptions1 = ref<any>([]);
const customFilter1 = _.debounce((query: any) => {
  if (!query) {
    filteredOptions1.value = [...productModelList.value];
    return;
  }
  filteredOptions1.value = productModelList.value.filter((option: any) => {
    return option?.productModelName
      ?.toLowerCase()
      .includes(query.toLowerCase());
  });
}, 300); // 延迟 300ms

const workshopSectionList = ref([]);
const getWorkshopSectionList = async () => {
  await request({
    url: `mdm/mdmworkshopsection/getList`,
    method: "post",
    data: {},
  }).then((res) => {
    workshopSectionList.value = res.data;
  });
};
const changeWorkshopSection = () => {
  searchParam.value.processEquipId = "";
  searchParam.value.processId = "";
  searchParam.value.equipId = "";
  searchParam.value.productModel = "";
  processList.value = [];
  getProcessListByWorkshopSection();
  getProcessEquipList();
  getEquipList();
  getProjectList();
  getProductModelList();
};
const getProcessListByWorkshopSection = async () => {
  if (searchParam.value.workshopSectionId) {
    await request({
      url: `mdm/mdmworkshopsection/getDetails`,
      method: "post",
      data: { id: searchParam.value.workshopSectionId },
    }).then((res) => {
      processList.value = res.data
        ? res.data.map(({ processId, processCode }) => ({
            id: processId,
            processCode,
          }))
        : [];
    });
  } else {
    await getProcessList();
  }
};
function resetHandle() {
  reset();
  getEquipList();
  getProcessList();
  getProjectList();
  getProductModelList();
  getProcessEquipList();
}

// 获取工序列表
const processEquipList: any = ref([]);
async function getProcessEquipList() {
  searchParam.value.processEquipId = "";
  processEquipList.value = [];
  filteredOptions2.value = [];
  const { data } = await request({
    // url: `/mdm/mdmprocess/getList`,
    url: "/mdm/mdmprocessequip/getList",
    method: "post",
    data: {
      workshopSectionId: searchParam.value.workshopSectionId,
      processId: searchParam.value.processId,
    },
  });
  processEquipList.value = data;
  filteredOptions2.value = data;
}
const filteredOptions2 = ref<any>([]);
// 使用 debounce 包装过滤方法
const customFilter2 = _.debounce((query: any) => {
  if (!query) {
    filteredOptions2.value = [...processEquipList.value];
    return;
  }
  filteredOptions2.value = processEquipList.value.filter((option: any) =>
    option.equipCode.toLowerCase().includes(query.toLowerCase())
  );
}, 300); // 延迟 300ms
function processEquipChange() {
  getEquipList();
  getProjectList();
  // getProductList();
  // getProjectList();
  getProductModelList();
}
</script>
